<template>
  <div class="max-w-2xl mx-auto space-y-6">
    <div v-if="state === 'complete'">
      <Card>
        <CardHeader class="text-center">
          <CardTitle class="flex items-center justify-center gap-2">
            <CheckCircle class="w-6 h-6 text-pink-500" />
            {{ t('colorTest.results.title') }}
          </CardTitle>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="text-center space-y-4">
            <div class="text-6xl font-bold text-primary">
              {{ getFinalScore() }}
            </div>
            <div :class="`text-xl font-semibold ${getRating().color}`">
              {{ getRating().text }}
            </div>
          </div>

          <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div class="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
              <div class="text-2xl font-bold text-green-600">{{ scores.correct }}</div>
              <div class="text-sm text-muted-foreground">{{ t('colorTest.results.correct') }}</div>
            </div>
            <div class="text-center p-4 bg-red-50 dark:bg-red-950 rounded-lg">
              <div class="text-2xl font-bold text-red-600">{{ scores.incorrect }}</div>
              <div class="text-sm text-muted-foreground">{{ t('colorTest.results.incorrect') }}</div>
            </div>
            <div class="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
              <div class="text-2xl font-bold text-blue-600">{{ getAccuracy() }}%</div>
              <div class="text-sm text-muted-foreground">{{ t('colorTest.results.accuracy') }}</div>
            </div>
            <div class="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg">
              <div class="text-2xl font-bold text-purple-600">{{ getAverageResponseTime() }}ms</div>
              <div class="text-sm text-muted-foreground">{{ t('colorTest.results.avgResponseTime') }}</div>
            </div>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="text-center p-4 bg-muted rounded-lg">
              <div class="text-xl font-bold">{{ getCongruencyStats().congruentAccuracy }}%</div>
              <div class="text-sm text-muted-foreground">{{ t('colorTest.results.congruentAccuracy') }}</div>
              <div class="text-xs text-muted-foreground mt-1">{{ t('colorTest.results.congruentDesc') }}</div>
            </div>
            <div class="text-center p-4 bg-muted rounded-lg">
              <div class="text-xl font-bold">{{ getCongruencyStats().incongruentAccuracy }}%</div>
              <div class="text-sm text-muted-foreground">{{ t('colorTest.results.incongruentAccuracy') }}</div>
              <div class="text-xs text-muted-foreground mt-1">{{ t('colorTest.results.incongruentDesc') }}</div>
            </div>
          </div>

          <div class="space-y-2">
            <h3 class="font-semibold">{{ t('colorTest.results.analysisTitle') }}</h3>
            <div class="text-sm text-muted-foreground space-y-1">
              <p>{{ t('colorTest.results.analysisItemsCompleted', { count: challenges.filter(c => c.isCorrect !== undefined).length }) }}</p>
              <p>{{ t('colorTest.results.analysisCongruentAccuracy', { acc: getCongruencyStats().congruentAccuracy }) }}</p>
              <p>{{ t('colorTest.results.analysisIncongruentAccuracy', { acc: getCongruencyStats().incongruentAccuracy }) }}</p>
              <p>{{ t('colorTest.results.analysisAvgResponse', { time: getAverageResponseTime() }) }}</p>
              <p v-if="getCongruencyStats().incongruentAccuracy < getCongruencyStats().congruentAccuracy - 10" class="text-orange-600">{{ t('colorTest.results.analysisSuggestion') }}</p>
            </div>
          </div>

          <div class="flex gap-4">
            <Button
              @click="resetTest"
              variant="outline"
              class="flex-1 border-2 border-slate-300 hover:border-slate-400 hover:bg-slate-50 text-slate-700 hover:text-slate-800 shadow-sm hover:shadow-md transition-all duration-300"
            >
              <RotateCcw class="w-4 h-4 mr-2" />
              {{ t('colorTest.results.retest') }}
            </Button>
            <Button
              @click="handleComplete"
              class="flex-1 bg-gradient-to-r from-pink-500 to-purple-600 hover:from-pink-600 hover:to-purple-700 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0"
            >
              <CheckCircle class="w-4 h-4 mr-2" />
              {{ t('colorTest.results.saveResult') }}
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>

    <Card v-if="state === 'testing'">
      <CardContent class="pt-6">
        <div class="flex justify-between items-center mb-2">
          <span class="text-sm">{{ t('colorTest.progress') }}</span>
          <span class="text-sm">{{ currentIndex }}/{{ totalChallenges }}</span>
        </div>
        <Progress :model-value="((currentIndex) / totalChallenges) * 100" />
      </CardContent>
    </Card>

    <Card>
      <template v-if="state === 'ready'">
        <CardHeader class="text-center">
          <CardTitle class="flex items-center justify-center gap-2">
            <Palette class="w-6 h-6 text-pink-500" />
            {{ t('colorTest.ready.title') }}
          </CardTitle>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="text-center space-y-4">
            <p class="text-muted-foreground">
              {{ t('colorTest.ready.description') }}
            </p>
            <div class="space-y-4">
              <div class="p-4 bg-muted rounded-lg">
                <h3 class="font-semibold mb-2">{{ t('colorTest.ready.rulesTitle') }}</h3>
                <div class="text-sm text-muted-foreground space-y-2">
                  <p>
                    {{ t('colorTest.ready.rule1_part1') }}
                    <strong>{{ t('colorTest.ready.rule1_part2') }}</strong>
                    {{ t('colorTest.ready.rule1_part3') }}
                  </p>
                  <p>
                    {{ t('colorTest.ready.rule2_part1') }}
                    <strong>{{ t('colorTest.ready.rule2_part2') }}</strong>
                    {{ t('colorTest.ready.rule2_part3') }}
                  </p>
                  <p>{{ t('colorTest.ready.rule3') }}</p>
                </div>
              </div>

              <div class="grid grid-cols-2 gap-4">
                <div class="text-center p-3 bg-green-50 dark:bg-green-950 rounded-lg">
                  <div class="text-lg font-bold" style="color: #10b981">{{ t('colors.green') }}</div>
                  <div class="text-xs text-muted-foreground mt-1">{{ t('colorTest.ready.exampleCongruent') }}</div>
                </div>
                <div class="text-center p-3 bg-red-50 dark:bg-red-950 rounded-lg">
                  <div class="text-lg font-bold" style="color: #ef4444">{{ t('colors.blue') }}</div>
                  <div class="text-xs text-muted-foreground mt-1">{{ t('colorTest.ready.exampleIncongruent') }}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="text-center">
            <Button
              size="lg"
              @click="startTest"
              class="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
            >
              <Palette class="w-5 h-5 mr-2" />
              {{ t('colorTest.ready.startTest') }}
            </Button>
          </div>
        </CardContent>
      </template>

      <template v-if="state === 'testing' && currentChallenge">
        <CardContent class="space-y-8">
          <div class="text-center space-y-6">
            <div class="text-sm text-muted-foreground">
              {{ currentChallenge.isCongruent ? t('colorTest.testing.questionCongruent') : t('colorTest.testing.questionIncongruent') }}
            </div>

            <!-- The word displayed in the target color -->
            <div
              class="text-8xl font-bold select-none"
              :style="{ color: currentChallenge.textColor }"
            >
              {{ currentChallenge.word }}
            </div>

            <div class="text-sm text-muted-foreground">
              {{ t('colorTest.testing.targetColor', { colorName: currentChallenge.targetColorName }) }}
            </div>
          </div>

          <div class="grid grid-cols-2 gap-4">
            <Button
              size="lg"
              variant="outline"
              @click="() => handleAnswer('color')"
              class="h-16 text-lg border-2 border-green-300 bg-gradient-to-br from-green-50 to-green-100 hover:from-green-100 hover:to-green-200 hover:border-green-400 text-green-700 hover:text-green-800 shadow-md hover:shadow-lg transition-all duration-300 flex flex-col items-center justify-center gap-1"
            >
              <div class="flex items-center gap-2">
                <Target class="w-5 h-5" />
                {{ t('colorTest.testing.answerColorMatch') }}
              </div>
              <div class="text-xs opacity-75">
                {{ t('colorTest.testing.answerColorMatchDesc') }}
              </div>
            </Button>
            <Button
              size="lg"
              variant="outline"
              @click="() => handleAnswer('text')"
              class="h-16 text-lg border-2 border-blue-300 bg-gradient-to-br from-blue-50 to-blue-100 hover:from-blue-100 hover:to-blue-200 hover:border-blue-400 text-blue-700 hover:text-blue-800 shadow-md hover:shadow-lg transition-all duration-300 flex flex-col items-center justify-center gap-1"
            >
              <div class="flex items-center gap-2">
                <Eye class="w-5 h-5" />
                {{ t('colorTest.testing.answerTextContent') }}
              </div>
              <div class="text-xs opacity-75">
                {{ t('colorTest.testing.answerTextContentDesc') }}
              </div>
            </Button>
          </div>

          <!-- Real-time stats -->
          <div class="grid grid-cols-3 gap-4 text-center">
            <div class="p-3 bg-green-50 dark:bg-green-950 rounded-lg">
              <div class="text-lg font-bold text-green-600">{{ scores.correct }}</div>
              <div class="text-xs text-muted-foreground">{{ t('colorTest.testing.statsCorrect') }}</div>
            </div>
            <div class="p-3 bg-red-50 dark:bg-red-950 rounded-lg">
              <div class="text-lg font-bold text-red-600">{{ scores.incorrect }}</div>
              <div class="text-xs text-muted-foreground">{{ t('colorTest.testing.statsIncorrect') }}</div>
            </div>
            <div class="p-3 bg-blue-50 dark:bg-blue-950 rounded-lg">
              <div class="text-lg font-bold text-blue-600">{{ getAccuracy() }}%</div>
              <div class="text-xs text-muted-foreground">{{ t('colorTest.testing.statsAccuracy') }}</div>
            </div>
          </div>
        </CardContent>
      </template>
    </Card>

    <Card>
      <CardContent class="pt-6">
        <h3 class="font-semibold mb-2">{{ t('colorTest.instructions.title') }}</h3>
        <ul class="text-sm text-muted-foreground space-y-1">
          <li>{{ t('colorTest.instructions.item1') }}</li>
          <li>{{ t('colorTest.instructions.item2') }}</li>
          <li>{{ t('colorTest.instructions.item3', { count: totalChallenges }) }}</li>
          <li>{{ t('colorTest.instructions.item4') }}</li>
          <li>{{ t('colorTest.instructions.item5') }}</li>
        </ul>
      </CardContent>
    </Card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n';
import { Palette, Timer, Target, RotateCcw, Eye, CheckCircle } from 'lucide-vue-next';

const { t } = useI18n();

const colors = [
  { name: t('colors.red'), value: '#ef4444', rgb: [239, 68, 68] },
  { name: t('colors.blue'), value: '#3b82f6', rgb: [59, 130, 246] },
  { name: t('colors.green'), value: '#10b981', rgb: [16, 185, 129] },
  { name: t('colors.yellow'), value: '#f59e0b', rgb: [245, 158, 11] },
  { name: t('colors.purple'), value: '#8b5cf6', rgb: [139, 92, 246] },
  { name: t('colors.orange'), value: '#f97316', rgb: [249, 115, 22] },
  { name: t('colors.pink'), value: '#ec4899', rgb: [236, 72, 153] },
  { name: t('colors.cyan'), value: '#06b6d4', rgb: [6, 182, 212] }
]

const state = ref('ready')
const challenges = ref([])
const currentChallenge = ref(null)
const currentIndex = ref(0)
const startTime = ref(0)
const scores = ref({ correct: 0, incorrect: 0 })

const totalChallenges = 20

const generateChallenge = () => {
  const isCongruent = Math.random() > 0.5
  const targetColor = colors[Math.floor(Math.random() * colors.length)]
  const textColor = isCongruent
    ? targetColor
    : colors[Math.floor(Math.random() * colors.length)]

  const challenge = {
    id: Date.now() + Math.random(),
    targetColor: targetColor.value,
    targetColorName: targetColor.name,
    textColor: textColor.value,
    word: textColor.name,
    isCongruent
  }

  return challenge
}

const startTest = () => {
  state.value = 'testing'
  currentIndex.value = 0
  scores.value = { correct: 0, incorrect: 0 }

  const newChallenges = Array.from({ length: totalChallenges }, generateChallenge)
  challenges.value = newChallenges
  currentChallenge.value = newChallenges[0]
  startTime.value = Date.now()
}

const handleAnswer = (answer) => {
  if (!currentChallenge.value) return

  const responseTime = Date.now() - startTime.value
  const isCorrect = (answer === 'color' && currentChallenge.value.isCongruent) ||
    (answer === 'text' && !currentChallenge.value.isCongruent)

  const updatedChallenge = {
    ...currentChallenge.value,
    userAnswer: answer,
    isCorrect,
    responseTime
  }

  challenges.value = challenges.value.map(c =>
    c.id === currentChallenge.value.id ? updatedChallenge : c
  )

  scores.value = {
    correct: scores.value.correct + (isCorrect ? 1 : 0),
    incorrect: scores.value.incorrect + (isCorrect ? 0 : 1)
  }

  // Move to next challenge
  const nextIndex = currentIndex.value + 1
  if (nextIndex >= totalChallenges) {
    state.value = 'complete'
  } else {
    currentIndex.value = nextIndex
    currentChallenge.value = challenges.value[nextIndex]
    startTime.value = Date.now()
  }
}

const resetTest = () => {
  state.value = 'ready'
  challenges.value = []
  currentChallenge.value = null
  currentIndex.value = 0
  scores.value = { correct: 0, incorrect: 0 }
}

const getAccuracy = () => {
  const total = scores.value.correct + scores.value.incorrect
  return total > 0 ? Math.round((scores.value.correct / total) * 100) : 0
}

const getAverageResponseTime = () => {
  const completedChallenges = challenges.value.filter(c => c.responseTime)
  if (completedChallenges.length === 0) return 0

  const totalTime = completedChallenges.reduce((sum, c) => sum + (c.responseTime || 0), 0)
  return Math.round(totalTime / completedChallenges.length)
}

const getCongruencyStats = () => {
  const congruentChallenges = challenges.value.filter(c => c.isCongruent && c.isCorrect !== undefined)
  const incongruentChallenges = challenges.value.filter(c => !c.isCongruent && c.isCorrect !== undefined)

  const congruentAccuracy = congruentChallenges.length > 0
    ? Math.round((congruentChallenges.filter(c => c.isCorrect).length / congruentChallenges.length) * 100)
    : 0

  const incongruentAccuracy = incongruentChallenges.length > 0
    ? Math.round((incongruentChallenges.filter(c => c.isCorrect).length / incongruentChallenges.length) * 100)
    : 0

  return { congruentAccuracy, incongruentAccuracy }
}

const getFinalScore = () => {
  const accuracy = getAccuracy()
  const avgResponseTime = getAverageResponseTime()
  const { congruentAccuracy, incongruentAccuracy } = getCongruencyStats()

  // Base score from accuracy
  let score = accuracy

  // Speed bonus (faster response = higher score)
  const speedBonus = Math.max(0, (2000 - avgResponseTime) / 2000) * 15
  score += speedBonus

  // Consistency bonus (similar performance on both types)
  const consistencyBonus = Math.max(0, 10 - Math.abs(congruentAccuracy - incongruentAccuracy) / 2)
  score += consistencyBonus

  return Math.min(100, Math.max(0, Math.round(score)))
}

const getRating = () => {
  const score = getFinalScore()
  if (score >= 90) return { text: t('colorTest.ratings.master'), color: 'text-yellow-500' }
  if (score >= 80) return { text: t('colorTest.ratings.excellent'), color: 'text-green-500' }
  if (score >= 70) return { text: t('colorTest.ratings.good'), color: 'text-blue-500' }
  if (score >= 60) return { text: t('colorTest.ratings.average'), color: 'text-gray-500' }
  return { text: t('colorTest.ratings.needsImprovement'), color: 'text-orange-500' }
}

const props = defineProps({
  onComplete: {
    type: Function,
    required: true
  }
})

const handleComplete = () => {
  const result = {
    testType: t('colorTest.testType'),
    score: getFinalScore(),
    details: t('colorTest.resultDetails', {
      acc: getAccuracy(),
      time: getAverageResponseTime(),
      count: challenges.value.filter(c => c.isCorrect !== undefined).length
    }),
    timestamp: new Date()
  }
  props.onComplete(result)
}
</script>